package org.jeecg.modules.iot.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.jeecg.modules.iot.model.SocketPort;
import org.jeecg.modules.iot.service.ISocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
@DS("tdengine")
public class SocketServiceImpl implements ISocketService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(SocketPort socket) {
        return jdbcTemplate.update(
                "INSERT INTO " + socket.getTableName() + " USING socket TAGS (?) (ts, power, out_time, energy, bt_stat, port_id, average_power) VALUES (?, ?, ?, ?, ?, ?, ?)",
                socket.getDeviceCode(), socket.getTs(), socket.getPower(), socket.getOutTime(), socket.getEnergy(), socket.getBtStat(), socket.getPortId(), socket.getAveragePower()
        );
    }

    @Override
    public int update(SocketPort socket) {
        return jdbcTemplate.update(
                "UPDATE socket SET ts = ?, power = ?, port_id = ?, out_time = ?, energy = ?, bt_stat = ?, average_power = ? WHERE port_id = ? AND device_code = ?",
                socket.getTs(), socket.getPower(), socket.getPortId(), socket.getOutTime(), socket.getEnergy(), socket.getBtStat(), socket.getAveragePower(), socket.getPortId(), socket.getDeviceCode()
        );
    }
    @Override
    public int delete(Integer portId, Long deviceCode) {
        return jdbcTemplate.update(
                "DELETE FROM socket WHERE port_id = ? AND device_code = ?",
                portId, deviceCode
        );
    }



    @Override
    public SocketPort queryByDeviceCode(Integer portId, String deviceCode) {
        try {
            String sql = "SELECT * FROM socket WHERE port_id = ? AND device_code = ? ORDER BY ts DESC LIMIT 1";
            return jdbcTemplate.queryForObject(sql, new Object[]{portId, deviceCode}, new BeanPropertyRowMapper<>(SocketPort.class));
        } catch (EmptyResultDataAccessException e) {
            return null;
        } catch (DataAccessException e) {
            throw new RuntimeException("Error querying data by port_id and device_code: " + portId + ", " + deviceCode, e);
        }
    }

}